import { gql, useLazyQuery } from "@apollo/client";
import create from "zustand";
import { devtools, persist } from "zustand/middleware";

import { Query } from "~/modules/api-server/types";
import { CurrentUser } from "~/modules/auth/models";
import { useTokenStore } from "~/modules/auth/store/use-token";
import { STORAGE_NAMES } from "~/modules/storage/storage-names";
export interface AuthState {
  user?: CurrentUser;
  authenticated: boolean;
}

export interface AuthActions {
  signIn: (user: CurrentUser) => void;
  signOut: () => void;
}

const initState = (): AuthState => {
  return {
    user: undefined,
    authenticated: false,
  };
};

export const useAuthStore = create<AuthState & AuthActions>(
  // @ts-ignore
  devtools(
    persist(
      (set, get, api) => ({
        ...initState(),
        signIn: (user: CurrentUser) => {
          set({ user, authenticated: true });
        },
        signOut: () => {
          set({ user: undefined, authenticated: false });
        },
      }),
      {
        name: STORAGE_NAMES.AUTH.name,
        version: STORAGE_NAMES.AUTH.version,
      }
    )
  )
);

export const GQL = gql`
  query me {
    me {
      id
      name
      userAirlines {
        airline {
          name
          logoUrl
        }
        department {
          name
        }
      }
    }
  }
`;

export const useAuth = () => {
  const { setToken } = useTokenStore();
  const { user, authenticated, signIn: storeSignIn } = useAuthStore();
  const [load] = useLazyQuery<Query>(GQL);
  const reload = async () => {
    const { data } = await load();
    const user = data?.me;
    const airlines = user?.userAirlines?.map((elem: any) => {
      return elem;
    });

    if (!user) {
      return;
    }
    storeSignIn({
      id: user.id,
      name: user.name,
      airlines: airlines ?? [],
    });
  };

  const signIn = (user: CurrentUser, token: string) => {
    setToken(token);
    storeSignIn(user);
    console.log(`-----登录成功---`);
  };
  return {
    authenticated,
    user,
    reload,
    signIn,
  };
};
